package model.micro
{
	import model.macro.RangedWeapon;
	import model.macro.Unit;
	import model.micro.projectiles.Projectile;
	import model.micro.projectiles.ProjectileType;
	import util.Random;
	import util.Settings;
	
	/**
	 * A battalion of soldiers with ranged weapons stationed in the castle.
	 */
	public class ArcherUnit
	{
		
		/** The unit this archer represents */
		public var unit:Unit;
		/** Y position */
		private var y:Number;
		/** A list of the number of seconds */
		private var wait_times:Vector.<Number>;
		/** Number of soldiers that can currently shoot */
		private var can_shoot:int;
		/** Stores a reference to the ranged weapon for easier access. */
		private var weapon:RangedWeapon;
		static private const SPEED_VARIATION:Number = 2 * Settings.METER;
		
		/**
		 * Create a new archer unit.
		 * @param	unit
		 */
		public function ArcherUnit(unit:Unit, fortress:MicroFortress)
		{
			this.unit = unit;
			y = Random.normal(fortress.getBoundingBox().top, Settings.METER);
			
			weapon = (unit.weapon as RangedWeapon);
			
			wait_times = new Vector.<Number>();
			for (var i:int = 0; i < unit.number_of_soldiers; i++)
			{
				wait_times.push(0.0);
			}
		}
		
		/**
		 * Called every frame.
		 */
		public function update(battle:Battle):void
		{
			can_shoot = 0;
			for (var i:int = wait_times.length - 1; i >= 0; i--)
			{
				if (wait_times[i] > Settings.getTimeStep())
				{
					wait_times[i] -= Settings.getTimeStep();
				}
				else
				{
					wait_times[i] = 0;
					can_shoot++;
				}
			}
		}
		
		/**
		 * Release an arrow.
		 * @param	battle
		 */
		public function fire(battle:Battle, angle:Number):void
		{
			for (var i:int = 0; i < wait_times.length; i++)
			{
				if (wait_times[i] <= 0)
				{
					var speed:Number = Random.normal(weapon.release_velocity, SPEED_VARIATION);
					var release_x:Number = battle.fortress.getBoundingBox().right;
					var release_y:Number = Random.uniform(y - Settings.METER, y + Settings.METER);
					var vx:Number = speed * Math.cos(angle);
					var vy:Number = speed * Math.sin(angle);
					
					battle.addProjectile(new Projectile(release_x, release_y, vx, vy, weapon.projectile_type));
					
					wait_times[i] = Random.normal((unit.weapon as RangedWeapon).reload_time, (unit.weapon as RangedWeapon).reload_time/10);
					can_shoot--;
				}
			}
		}
	}
}